<script setup lang="ts" name="Dept">
import { QForm, QTable, type FormItemRows, type TableColums } from '@meetjs/element-plus-kit'
import { checkPermission } from '@/utils/permission'
import { getDicts } from '@/api/system/dict/index'
import type { IGetDictsRes } from '@/api/system/dict/type'
import { delDept, listDept } from '@/api/system/dept/index'
import type { DeptList, QueryParams } from '@/api/system/dept/type'
import { warnBox } from '@/utils/utils'
import EditDialog from './components/EditDialog.vue'
import { ElMessage } from 'element-plus'
import { handleTree } from '@/utils'
import { formatDate } from '@/utils/day'

// form
const formValue = ref<QueryParams>({
	deptName: '',
	status: '',
	cascader: ''
})

const sysNormalDisable = ref<IGetDictsRes>([])

const formOptions = ref<FormItemRows[]>([
	{
		type: 'input',
		label: '部门名称',
		prop: 'deptName'
	},
	{
		type: 'select',
		label: '状态',
		prop: 'status',
		options: sysNormalDisable as unknown as any,
		attrs: {
			style: 'width: 200px'
		}
	}
])

// table
const loading = ref(false)
const tableData = ref<DeptList[]>([])
const expandAll = ref(true)
const columns = ref<TableColums[]>([
	{
		label: '部门名称',
		prop: 'deptName',
		align: 'left'
	},
	{
		label: '排序',
		prop: 'orderNum',
		align: 'left'
	},
	{
		label: '状态',
		prop: 'status',
		align: 'center'
	},
	{
		label: '创建时间',
		prop: 'createTime',
		showOverflowTooltip: true,
		formatter: v => formatDate(v.createTime),
		align: 'left'
	},
	{
		prop: 'action',
		fixed: 'right',
		label: '操作',
		width: 160,
		align: 'center'
	}
])

// dialog
const editDialogRef = useTemplateRef('editDialogRef')

const getTableData = async () => {
	loading.value = true
	try {
		const res = await listDept({
			...formValue.value
		})

		tableData.value = handleTree(res.data || [])
	} catch (error) {
		console.error('获取部门列表失败:', error)
		tableData.value = []
	} finally {
		loading.value = false
	}
}

const handleAdd = (row?: DeptList) => {
	editDialogRef.value?.init('add', undefined, row?.id, tableData.value)
}

const handleEdit = (row: DeptList) => {
	editDialogRef.value?.init('edit', row, undefined, tableData.value)
}

const handleDelete = async (row: DeptList) => {
	await warnBox({ title: '提示' })
	await delDept(row.id)
	ElMessage.success('删除成功')
	getTableData()
}

const isShowTable = ref(true)
const toggleExpandAll = () => {
	expandAll.value = !expandAll.value
}

watch(
	() => expandAll.value,
	() => {
		isShowTable.value = false
		nextTick(() => {
			isShowTable.value = true
		})
	}
)

function init() {
	getDicts('sys_sys_normal_disable').then(data => {
		sysNormalDisable.value = data
	})
}

onMounted(() => {
	init()
	getTableData()
})
</script>

<template>
	<div class="table-page-box">
		<div class="filter-box">
			<QForm
				inline
				:model="formValue"
				:form-options="formOptions"
				:buttons="['search', 'reset']"
				@search="getTableData"
				@reset="getTableData"
			/>
		</div>
		<div class="table-box">
			<QTable
				v-if="isShowTable"
				:data="tableData"
				:columns="columns"
				:loading="loading"
				style="width: 100%"
				:tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
				row-key="id"
				:default-expand-all="expandAll"
				@pageChange="getTableData"
			>
				<template #headerLeft>
					<el-button
						v-if="checkPermission(['system:dept:add'])"
						type="primary"
						@click="handleAdd()"
					>
						新增
					</el-button>
					<el-button @click="toggleExpandAll"> 展开/折叠 </el-button>
				</template>
				<template #status="{ row }">
					<DictTag
						:value="row.status"
						:options="sysNormalDisable"
					/>
				</template>
				<template #action="{ row }">
					<el-button
						v-if="checkPermission(['system:dept:edit'])"
						type="primary"
						link
						@click="handleEdit(row)"
					>
						修改
					</el-button>
					<el-button
						v-if="checkPermission(['system:dept:add'])"
						type="primary"
						link
						@click="handleAdd(row)"
					>
						新增
					</el-button>
					<el-button
						v-if="checkPermission(['system:dept:remove']) && row.parentId !== 0"
						type="danger"
						link
						@click="handleDelete(row)"
					>
						删除
					</el-button>
				</template>
			</QTable>
		</div>
		<EditDialog
			ref="editDialogRef"
			@refresh="getTableData"
		/>
	</div>
</template>
